<template>
  <div class="admin-dashboard" v-reveal="{ delay: 60 }">
    <div class="container">
      <div v-if="!isLoggedIn" class="login-section">
        <el-card class="login-card">
          <template #header>
            <h2>管理员登录</h2>
          </template>
          
          <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入管理员密码"
                show-password
                @keyup.enter="handleLogin"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="handleLogin" :loading="loading" style="width: 100%;">
                登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
      
      <div v-else class="dashboard-content">
        <el-page-header @back="goBack" title="返回首页">
          <template #content>
            <span class="page-title">管理员后台</span>
          </template>
        </el-page-header>
        
        <div class="stats-section" v-reveal="{ delay: 120 }">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="6" v-for="(stat, idx) in stats" :key="stat.id">
              <el-card class="stat-card" shadow="hover" v-reveal="{ delay: 160 + idx * 80, distance: 12 }">
                <div class="stat-content">
                  <div class="stat-icon">
                    <el-icon :size="40" :color="stat.color">
                      <component :is="stat.icon" />
                    </el-icon>
                  </div>
                  <div class="stat-info">
                    <h3>{{ stat.value }}</h3>
                    <p>{{ stat.label }}</p>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        
        <div class="management-section" v-reveal="{ delay: 120 }">
          <h2>管理功能</h2>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" v-for="(module, idx) in managementModules" :key="module.id">
              <el-card class="module-card" shadow="hover" @click="navigateToModule(module.path)" v-reveal="{ delay: 160 + idx * 80, distance: 12 }">
                <div class="module-content">
                  <div class="module-icon">
                    <el-icon :size="50" color="#4CAF50">
                      <component :is="module.icon" />
                    </el-icon>
                  </div>
                  <h3>{{ module.title }}</h3>
                  <p>{{ module.description }}</p>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        
        <div class="quick-actions" v-reveal="{ delay: 120 }">
          <h2>快速操作</h2>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="6" v-for="action in quickActions" :key="action.id">
              <el-button 
                :type="action.type" 
                size="large" 
                @click="action.handler"
                style="width: 100%; margin-bottom: 10px;"
                v-reveal="{ delay: 160, distance: 8 }"
              >
                <el-icon style="margin-right: 8px;">
                  <component :is="action.icon" />
                </el-icon>
                {{ action.label }}
              </el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Document, 
  User, 
  Picture, 
  Money, 
  Setting,
  Plus,
  Refresh,
  Download,
  Upload
} from '@element-plus/icons-vue'
import { getNewsData, getStaffData, getGalleryData, getDonorData } from '../api/serverApi'

export default {
  name: 'AdminDashboard',
  components: {
    Document,
    User,
    Picture,
    Money,
    Setting,
    Plus,
    Refresh,
    Download,
    Upload
  },
  setup() {
    const router = useRouter()
    const isLoggedIn = ref(false)
    const loading = ref(false)
    const loginFormRef = ref()
    
    const loginForm = ref({
      password: ''
    })
    
    const loginRules = {
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ]
    }
    
    const stats = ref([
      {
        id: 1,
        label: '公告数量',
        value: 0,
        icon: 'Document',
        color: '#4CAF50'
      },
      {
        id: 2,
        label: '团队成员',
        value: 0,
        icon: 'User',
        color: '#2196F3'
      },
      {
        id: 3,
        label: '画廊图片',
        value: 0,
        icon: 'Picture',
        color: '#FF9800'
      },
      {
        id: 4,
        label: '捐赠者',
        value: 0,
        icon: 'Money',
        color: '#9C27B0'
      }
    ])
    
    const managementModules = ref([
      {
        id: 1,
        title: '公告管理',
        description: '添加、编辑、删除服务器公告',
        icon: 'Document',
        path: '/admin/announcements'
      },
      {
        id: 2,
        title: '团队成员管理',
        description: '管理服务器团队成员信息',
        icon: 'User',
        path: '/admin/staff'
      },
      {
        id: 3,
        title: '画廊管理',
        description: '管理服务器截图和精彩瞬间',
        icon: 'Picture',
        path: '/admin/gallery'
      },
      {
        id: 4,
        title: '捐赠者管理',
        description: '查看和管理捐赠者信息',
        icon: 'Money',
        path: '/admin/donors'
      },
      {
        id: 5,
        title: '密码修改',
        description: '修改管理员登录密码',
        icon: 'Setting',
        path: '/admin/password'
      }
    ])
    const quickActions = ref([])
    

    const handleLogin = async () => {
      if (!loginFormRef.value) return
      
      try {
        await loginFormRef.value.validate()
        loading.value = true
        
        // 模拟登录验证
        setTimeout(() => {
          if (loginForm.value.password === 'admin123') {
            isLoggedIn.value = true
            localStorage.setItem('adminLoggedIn', 'true')
            ElMessage.success('登录成功')
            refreshStats()
          } else {
            ElMessage.error('密码错误')
          }
          loading.value = false
        }, 1000)
      } catch (error) {
        console.error('登录验证失败:', error)
      }
    }

    const goBack = () => {
      router.push('/')
    }

    const navigateToModule = (path) => {
      router.push(path)
    }

    const refreshStats = () => {
      stats.value[0].value = getNewsData().length
      stats.value[1].value = getStaffData().length
      stats.value[2].value = getGalleryData().length
      stats.value[3].value = getDonorData().length
      ElMessage.success('数据已刷新')
    }

    const exportData = () => {
      const data = {
        news: getNewsData(),
        staff: getStaffData(),
        gallery: getGalleryData(),
        donors: getDonorData()
      }
      
      const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = 'kbb-server-data.json'
      a.click()
      URL.revokeObjectURL(url)
      ElMessage.success('数据导出成功')
    }

    const importData = () => {
      ElMessage.info('导入功能开发中...')
    }

    // 依赖已定义的方法，放在方法定义之后再赋值，避免初始化时引用未定义
    quickActions.value = [
      {
        id: 1,
        label: '添加公告',
        icon: 'Plus',
        type: 'primary',
        handler: () => router.push('/admin/announcements')
      },
      {
        id: 2,
        label: '刷新数据',
        icon: 'Refresh',
        type: 'info',
        handler: refreshStats
      },
      {
        id: 3,
        label: '导出数据',
        icon: 'Download',
        type: 'success',
        handler: exportData
      },
      {
        id: 4,
        label: '导入数据',
        icon: 'Upload',
        type: 'warning',
        handler: importData
      }
    ]

    onMounted(() => {
      const loggedIn = localStorage.getItem('adminLoggedIn')
      if (loggedIn === 'true') {
        isLoggedIn.value = true
        refreshStats()
      }
    })

    return {
      isLoggedIn,
      loading,
      loginForm,
      loginFormRef,
      loginRules,
      stats,
      managementModules,
      quickActions,
      handleLogin,
      goBack,
      navigateToModule,
      refreshStats,
      exportData,
      importData
    }
  }
}
</script>

<style scoped>
.admin-dashboard {
  padding: 20px 0;
}

.login-section {
  max-width: 400px;
  margin: 100px auto;
}

.login-card {
  text-align: center;
}

.login-card h2 {
  color: #4CAF50;
  margin: 0;
}

.dashboard-content {
  margin-top: 20px;
}

.page-title {
  font-size: 1.5rem;
  font-weight: bold;
  color: #4CAF50;
}

.stats-section {
  margin: 30px 0;
}

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
}

.stat-info h3 {
  font-size: 2rem;
  color: #4CAF50;
  margin: 0;
}

.stat-info p {
  color: #666;
  margin: 5px 0 0 0;
}

.management-section {
  margin: 40px 0;
}

.management-section h2 {
  color: #4CAF50;
  margin-bottom: 20px;
}

.module-card {
  cursor: pointer;
  transition: transform 0.3s;
  height: 100%;
}

.module-card:hover {
  transform: translateY(-5px);
}

.module-content {
  text-align: center;
  padding: 20px;
}

.module-icon {
  margin-bottom: 20px;
}

.module-content h3 {
  color: #4CAF50;
  margin-bottom: 10px;
}

.module-content p {
  color: #666;
  line-height: 1.6;
}

.quick-actions {
  margin: 40px 0;
}

.quick-actions h2 {
  color: #4CAF50;
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .stat-content {
    flex-direction: column;
    gap: 10px;
  }
  
  .stat-info h3 {
    font-size: 1.5rem;
  }
  
  .module-card {
    margin-bottom: 20px;
  }
}
</style> 